<?php
/**
 * Created by PhpStorm.
 * User: XZR
 * Date: 2018/8/1
 * Time: 15:21
 */

namespace Api\Controller;
use Api\Model\UserModel;
use Api\Model\WeixinUserModel;
use Common\Util\EncryUtils;

//用户
class UserController extends  AuthController
{
    //注册
    public function register(){
        $this->validateParam(array('name','hospital'));
        $name = $this->getGetParam('name','');
        $hospital = $this->getGetParam('hospital','');
        $phone = $this->getGetParam('phone','');
        $title = $this->getGetParam('title','');
        $duty = $this->getGetParam('duty','');
        $openid = EncryUtils::decrypt($this->getGetParam('token'));

        if(UserModel::singleton()->getByOpenid($openid)){
            $rst['result']=201;
            $rst['msg']='已注册';
            $this->formatjson($rst);
        }

        $res=UserModel::singleton()->addUser($name,$hospital,$phone,$title,$duty,$openid);
        if($res){
            $rst['result']=200;
            $rst['msg']='注册成功';
        }else{
            $rst['result']=202;
            $rst['msg']='系统繁忙,请稍后重试';
        }
        $this->formatjson($rst);
    }

    public function info(){
        $user_id= $this->userId;
        $openid=EncryUtils::decrypt($this->getGetParam('token'));
        $info = UserModel::singleton()->getById($user_id);
        $weixinInfo = WeixinUserModel::singleton()->getAvatarUrlByOpneid($openid);
        $info['avatarurl']=$weixinInfo['avatarurl'];
        $info['nickname']=$weixinInfo['nickname'];
        $rst =array();
        $rst['result']=200;
        $rst['info']=$info;
        $this->formatjson($rst);
    }

    public function update(){
        $this->validateParam(array('name','hospital'));
        $name= $this->getPostParam('name','');
        $hospital= $this->getPostParam('hospital','');
        $phone= $this->getPostParam('phone','');
        $title= $this->getPostParam('title','');
        $duty = $this->getGetParam('duty','');

        $res=UserModel::singleton()->updateUser($name,$hospital,$phone,$title,$duty,$this->userId);
        if($res!==false){
            $rst['result']=200;
            $rst['msg']='修改成功';
        }else{
            $rst['result']=202;
            $rst['msg']='修改失败';
        }
        $this->formatjson($rst);
    }
}